package org.xxpay.pay.channel.haitian;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.springframework.stereotype.Component;
import org.xxpay.common.http.HttpRequestTemplate;
import org.xxpay.common.util.sign.SignUtils;
import org.xxpay.common.util.str.StringUtils;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.entity.TransOrder;
import org.xxpay.pay.channel.BaseTrans;
import org.xxpay.pay.channel.shengfutong.SftpayConfig;
import org.xxpay.pay.channel.zhifu.ZhifuConfig;

import java.util.Map;

@Component
public class HaitianTransService extends BaseTrans {
    private final static String logPrefix = "【海天】";
    @Override
    public String getChannelName() {
        return SftpayConfig.CHANNEL_NAME;
    }
    @Override
    public JSONObject balance(String payParam) {
        JSONObject retObj = buildRetObj();
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, "没有余额查询接口");
        return retObj;
    }
    /**
     * 代付订单
     *
     * @param transOrder
     * @return
     */
    @Override
    public JSONObject trans(TransOrder transOrder){
        JSONObject retObj = buildRetObj();
        HaitianConfig config = new HaitianConfig(getTransParam(transOrder));
        Map<String, Object> params = Maps.newHashMap();
        setParams(transOrder,config,params);
        _log.info("{}申请代付请求参数：{}", logPrefix, params.toString());
        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);
        JSONObject origin = requestTemplate.postForObject(getReqUrl(config.getRequestUrl(), HaitianConfig.REQ_TRANS_Fixx), params, JSONObject.class);
        _log.info("{}代付查询响应参数：{}", logPrefix, origin.toJSONString());
        retObj.put("isSuccess", false);
        retObj.put("transOrderId", transOrder.getTransOrderId());
        if(StringUtils.equals(origin.getString("code"),"1")){
            JSONObject backData = JSONObject.parseObject(origin.getString("data"));
            retObj.put("status", Integer.valueOf(backData.getString("status")));
            retObj.put("channelOrderNo", origin.getString("cashOrderId"));
            retObj.put("channelObj", origin);
            return retObj;
        }
        // 1. 处理中 2. 成功 3. 失败
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, origin.getString("msg"));
        retObj.put("channelErrCode", origin.getString("status"));
        retObj.put("isSuccess", false);
        return retObj;
    }

    /**
     * 订单查询接口
     *
     * @param transOrder
     * @return
     */
    @Override
    public JSONObject query(TransOrder transOrder) {
        JSONObject retObj = buildRetObj();
        HaitianConfig config = new HaitianConfig(getTransParam(transOrder));
        String payOrderId = transOrder.getTransOrderId();
        _log.info("{}开始查询代付通道订单,payOrderId={}", logPrefix, payOrderId);
        Map<String, Object> params = Maps.newHashMap();
        params.put("version",HaitianConfig.VIL_VERSION_VLAUE);
        params.put("merchant_number", config.getAppId());
        params.put("order_id", transOrder.getTransOrderId());
        params.put("sign", getSign(params, config.getPrivateKey()));
        _log.info("{}代付查询请求参数：{}", logPrefix, params.toString());
        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);
        JSONObject origin = requestTemplate.postForObject(getReqUrl(config.getRequestUrl(), HaitianConfig.REQ_TRANS_Fixx), params, JSONObject.class);
        retObj.put("isSuccess", false);
        retObj.put("transOrderId", transOrder.getTransOrderId());
        if(StringUtils.equals(origin.getString("code"),"1")){
            JSONObject backData = JSONObject.parseObject(origin.getString("data"));
            //处理中
            int status = 1;
            if(StringUtils.equals(backData.getString("status"),"2")){
                //成功
                status = 2;
            }else if (StringUtils.equals(backData.getString("status"),"3")){
                //失败
                status = 3;
            }
            retObj.put("channelOrderNo", "");
            retObj.put("isSuccess", true);
            // 1. 处理中 2. 成功 3. 失败
            retObj.put("status", status);
            return retObj;
        }
        // 1. 处理中 2. 成功 3. 失败
        retObj.put("status", 3);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, "下单失败[" + origin.getString("msg") + "]");
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        return retObj;
    }

    //设置请求参数
    private void setParams(TransOrder transOrder,HaitianConfig config,Map<String,Object> params){

        params.put("version", HaitianConfig.VIL_VERSION_VLAUE);
        params.put("merchant_number", config.getAppId());
        params.put("paymode_id",config.getPayMode());
        params.put("order_id", transOrder.getTransOrderId());
        params.put("amount", AmountUtil.convertCent2Dollar(String.valueOf(transOrder.getAmount())));
        params.put("bank_title", transOrder.getBankName());
        params.put("number", transOrder.getAccountNo());
        params.put("name", transOrder.getAccountName());
        params.put("province", transOrder.getProvince());
        params.put("city", transOrder.getCity());
        params.put("sign", getSign(params, config.getPrivateKey()));

    }

    //获取签名
    private String getSign(Map<String,Object> params, String key){
        String signTxt = SignUtils.parameterText(params);
        _log.info("{}海天支付签名字符串：{}", logPrefix, signTxt);
        String sign = SignUtils.MD5.createSign(signTxt, "&key="+key, SignUtils.CHARSET_UTF8);
        return sign;
    }
}
